package com.wdz;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wdz.article.entity.Article;
import com.wdz.article.service.IArticleService;
import com.wdz.article_comment.entity.ArticleComment;
import com.wdz.article_comment.service.IArticleCommentService;
import com.wdz.category.service.ICategoryService;
import com.wdz.redis.ApplicationContextUtil;
import com.wdz.redis.RedisUtil;
import com.wdz.systemlogs.entity.SystemLogs;
import com.wdz.systemlogs.service.ISystemLogsService;
import com.wdz.utils.RedisFieldName;
import net.hasor.spring.boot.EnableHasor;
import net.hasor.spring.boot.EnableHasorWeb;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * 后台首页控制台数据统计接口
 * @author wuchuancheng
 */
@SpringBootApplication
@EnableFeignClients
@EnableScheduling
@Component("ArticleApplication")
/**
 * hasor配置项
 */
@EnableHasor()
@EnableHasorWeb()
/**
 * 扫描所有的mapper
 */
@MapperScan({"com.wdz.*.mapper","com.wdz.tofs.*.mapper"})
//@EnableTransactionManagement //开启全局事务
public class ArticleApplication {
    @Value("${server.port}")
    private String port;

    @Value("${spring.profiles.active}")
    public String tenant;

    public static void main(String[] args) {

        SpringApplication.run(ArticleApplication.class, args);
        //SpringApplicationBuilder builder = new SpringApplicationBuilder(ArticleApplication.class);
        //builder.bannerMode(Banner.Mode.OFF).run(args);
        //CronUtil.start();
        ArticleApplication articleApplication = (ArticleApplication) ApplicationContextUtil.getBean("ArticleApplication");
        //清空缓存
        RedisUtil redisUtil = new RedisUtil("redisTemplate2");
        redisUtil.clear();
        //articleApplication.setIndexDash();
        System.out.println("启动成功 ！"+articleApplication.port);
        System.out.println("\n" +
                ".____    .__         __      __             _____.___.__                 .___  .____    ____________   _______________ _____.___.________   ____ ___\n" +
                "|    |   |__|__ __  /  \\    /  \\ ____   ____\\__  |   |__| ____    ____   |   | |    |   \\_____  \\   \\ /   /\\_   _____/ \\__  |   |\\_____  \\ |    |   \\\n" +
                "|    |   |  |  |  \\ \\   \\/\\/   // __ \\ /    \\/   |   |  |/    \\  / ___\\  |   | |    |    /   |   \\   Y   /  |    __)_   /   |   | /   |   \\|    |   /\n" +
                "|    |___|  |  |  /  \\        /\\  ___/|   |  \\____   |  |   |  \\/ /_/  > |   | |    |___/    |    \\     /   |        \\  \\____   |/    |    \\    |  /\n" +
                "|_______ \\__|____/    \\__/\\  /  \\___  >___|  / ______|__|___|  /\\___  /  |___| |_______ \\_______  /\\___/   /_______  /  / ______|\\_______  /______/\n" +
                "        \\/                 \\/       \\/     \\/\\/              \\//_____/                 \\/       \\/                 \\/   \\/               \\/\n");

    }

    private IArticleService iArticleService;
    private ICategoryService iCategoryService;
    private ISystemLogsService iSystemLogsService;
    @Autowired
    private IArticleCommentService iArticleCommentService;


    @Autowired
    public void setArticleService(IArticleService iArticleService){
        this.iArticleService = iArticleService;
    }

    @Autowired
    public void setCategoryService(ICategoryService iCategoryService) {
        this.iCategoryService = iCategoryService;
    }

    @Autowired
    public void setSystemLogsService(ISystemLogsService iSystemLogsService){
        this.iSystemLogsService = iSystemLogsService;
    }

    private static final Log log = LogFactory.get();

    //将数据统计需要的数据写入redis 每天凌晨执行
    @Scheduled(cron = "0 0 0 * * ?")
    public void setIndexDash(){
        log.info("将数据统计写入redis的定时任务启动"+DateUtil.now());
        RedisUtil redisUtil = RedisUtil.init();
        String rn = RedisFieldName.INDEXDASHBOARD;
        //文章数量
        redisUtil.hset(rn,"articleNumber",iArticleService.selectCount(null));
        //分类数量
        redisUtil.hset(rn,"categoryNumber",iCategoryService.selectCount(null));
        //网站访问数量
        redisUtil.hset(rn,"visits",iSystemLogsService.selectCount(null));
        //留言数量
        redisUtil.hset(rn,"remarkNumber",iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("type=2")));
        //昨日的网站访问数量
        redisUtil.hset(rn,"zr",iSystemLogsService.selectCount(new EntityWrapper<SystemLogs>().where("create_date >= {0} and create_date <= {1}", DateUtil.beginOfDay(DateUtil.yesterday()),DateUtil.endOfDay(DateUtil.yesterday()))));
        //今天的网站访问数量
        redisUtil.hset(rn,"jr",iSystemLogsService.selectCount(new EntityWrapper<SystemLogs>().where("create_date >= {0}",DateUtil.beginOfDay(DateUtil.date()))));
        //昨日的留言量
        redisUtil.hset(rn,"zrlyl",iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("create_date >= {0} and create_date <= {1} and type=2", DateUtil.beginOfDay(DateUtil.yesterday()),DateUtil.endOfDay(DateUtil.yesterday()))));
        //今日的留言量
        redisUtil.hset(rn,"jrlyl",iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("create_date >= {0} and type=2",DateUtil.beginOfDay(DateUtil.date()))));
        //获取7天前到今天每一天的网站访问量
        //JSONObject jsonObject = new JSONObject();
        Map<String,Object> map = new TreeMap<>();
        //jsonObject.append(DateUtil.beginOfDay(DateUtil.offset(DateUtil.date(), DateField.DAY_OF_MONTH, -7)).toDateStr(),iSystemLogsService.selectCount(new EntityWrapper<SystemLogs>().where("create_date >= {0} and create_date <= {1}", DateUtil.beginOfDay(DateUtil.offset(DateUtil.date(), DateField.DAY_OF_MONTH, -7)),DateUtil.endOfDay(DateUtil.offset(DateUtil.date(), DateField.DAY_OF_MONTH, -7)))));
        Date date;
        for(int i=7;i>=0;i--){
            date = DateUtil.offset(DateUtil.date(), DateField.DAY_OF_MONTH, -i);
            if(i == 0){
                map.put("今天",iSystemLogsService.selectCount(new EntityWrapper<SystemLogs>().where("create_date >= {0} and create_date <= {1}", DateUtil.beginOfDay(date),DateUtil.endOfDay(date))));
                break;
            }
            map.put(i+"天前",iSystemLogsService.selectCount(new EntityWrapper<SystemLogs>().where("create_date >= {0} and create_date <= {1}", DateUtil.beginOfDay(date),DateUtil.endOfDay(date))));
        }
        redisUtil.hset(rn,"7tq", map);
        //关注度较高的前5篇文章
        redisUtil.hset(rn,"q5p",iArticleService.selectPage(new Page<>(1,5),new EntityWrapper<Article>().where("type=0").orderBy("count",false).orderBy("praise",false).orderBy("comments",false).orderBy("collections",false)).getRecords());
    }

}
